import 'package:dio/dio.dart';
import 'package:flower/components/cached_image_widget.dart';
import 'package:flower/components/custom_toast.dart';
import 'package:flower/config/service_url.dart';
import 'package:flower/model/base_model.dart';
import 'package:flower/model/order_list.dart';
import 'package:flower/pages/tabs/user/children/comment_add.dart';
import 'package:flower/utils/http_util.dart';
import 'package:flutter/material.dart';

class OrderList extends StatefulWidget {
  const OrderList({super.key});

  @override
  State<OrderList> createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> {
  final List<String> orderStatus = [
    '全部',
    '待支付',
    '待发货',
    '配送中',
    '已完成',
    '已取消',
    "退款"
  ];
  String _currentStatus = '全部';

  List<OrderData> orderListData = [];

  @override
  void initState() {
    super.initState();
    _queryOrderListData();
  }

  void _queryOrderListData() async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["status"] = _statusToCode(_currentStatus);

    Response result = await HttpUtil.get(listOrder, queryParameters: map);
    setState(() {
      OrderModel orderListModel = OrderModel.fromJson(result.data);
      orderListData = orderListModel.data!;
    });
  }

  int _statusToCode(String status) {
    switch (status) {
      case '待支付':
        return 1;
      case '待发货':
        return 2;
      case '配送中':
        return 3;
      case '已完成':
        return 4;
      case '已取消':
        return 5;
      case '退款':
        return 6;
      case '全部':
      default:
        return 0;
    }
  }

  void _onTabChanged(int index) {
    setState(() {
      _currentStatus = orderStatus[index];
    });
    _queryOrderListData();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: orderStatus.length,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('我的订单'),
          titleTextStyle: const TextStyle(fontSize: 16, color: Colors.black),
          centerTitle: true,
          bottom: TabBar(
            isScrollable: true,
            indicatorColor:
                Color(int.parse('fa436a', radix: 16)).withAlpha(255),
            labelColor: Color(int.parse('fa436a', radix: 16)).withAlpha(255),
            tabs: orderStatus.map((status) => Tab(text: status)).toList(),
            onTap: _onTabChanged,
          ),
        ),
        body: TabBarView(
          children: orderStatus.map((status) {
            return OrderListInfo(
              status: status,
              orderListData: orderListData,
            );
          }).toList(),
        ),
      ),
    );
  }
}

class OrderListInfo extends StatelessWidget {
  final String status;
  final List<OrderData> orderListData;

  const OrderListInfo({
    super.key,
    required this.status,
    required this.orderListData,
  });

  // 取消订单
  void handleCancel(String number) async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["number"] = number;

    Response result = await HttpUtil.post(cancelOrder, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      CustomToast.showSuccessToast("取消成功");
      // 从orderListData中移除这一项
      orderListData.removeWhere((element) => element.number == number);
    }
  }

  // 确认收货
  void handleConfirm(String number) async {
    Map<String, dynamic> map = <String, dynamic>{};
    map["number"] = number;

    Response result = await HttpUtil.post(confirmOrder, queryParameters: map);
    BaseModel baseModel = BaseModel.fromJson(result.data);
    if (baseModel.code == 1) {
      CustomToast.showSuccessToast("收货成功");
      // 从orderListData中移除这一项
      orderListData.removeWhere((element) => element.number == number);
    }
  }

  // 付款
  void handlePay(String number) async {
    CustomToast.showSuccessToast("努力赶工中...");
    // Map<String, dynamic> map = <String, dynamic>{};
    // map["number"] = number;

    // Response result = await HttpUtil.post(confirmOrder, queryParameters: map);
    // BaseModel baseModel = BaseModel.fromJson(result.data);
    // if (baseModel.code == 1) {
    //   CustomToast.showSuccessToast("取消成功");
    //   // 从orderListData中移除这一项
    //   orderListData.removeWhere((element) => element.number == number);
    // }
  }

  @override
  Widget build(BuildContext context) {
    var border = BorderSide(
        width: 1, color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255));
    var boxDecoration = BoxDecoration(border: Border(bottom: border));
    return ListView.builder(
        itemCount: orderListData.length,
        itemBuilder: (context, index) {
          return InkWell(
            onTap: () {
              // Navigator.of(context).push(
              //   MaterialPageRoute(
              //     builder: (context) => OrderDetail(
              //       orderId: orderListData[index].id,
              //     ),
              //   ),
              // );
            },
            child: Container(
              padding: const EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(
                          width: 5,
                          color: Color(int.parse('f5f5f5', radix: 16))
                              .withAlpha(255)))),
              child: Column(children: [
                buildCreateTime(boxDecoration, index),
                buildProductList(index),
                buildAmount(boxDecoration, index),
                buildOrderOperate(context, index)
              ]),
            ),
          );
        });
  }

  // 构建订单操作
  Container buildOrderOperate(BuildContext context, int index) {
    int status = orderListData[index].status;
    return Container(
      padding: const EdgeInsets.only(right: 5),
      height: 40,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Visibility(
            visible: status == 0,
            child: TextButton(
              onPressed: () {
                handleCancel(orderListData[index].number);
              },
              child: Text("取消订单",
                  style: TextStyle(
                      fontSize: 14,
                      color: Color(int.parse('303133', radix: 16))
                          .withAlpha(255))),
            ),
          ),
          Visibility(
              visible: status == 3,
              child: TextButton(
                onPressed: () {
                  CustomToast.showWarningToast("该功能正在努力开发中~");
                },
                child: Text("查看物流",
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(int.parse('303133', radix: 16))
                            .withAlpha(255))),
              )),
          Visibility(
              visible: status == 1,
              child: TextButton(
                onPressed: () {
                  handlePay(orderListData[index].number);
                },
                child: Text("立即付款",
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(int.parse('fa436a', radix: 16))
                            .withAlpha(255))),
              )),
          Visibility(
              visible: status == 3,
              child: TextButton(
                onPressed: () {
                  handleConfirm(orderListData[index].number);
                },
                child: Text("确认收货",
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(int.parse('fa436a', radix: 16))
                            .withAlpha(255))),
              )),
          Visibility(
              visible: status == 4,
              child: TextButton(
                onPressed: () {
                  // CustomToast.showWarningToast("该功能正在努力开发中~");
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => CommentAdd(
                        number: orderListData[index].number,
                      ),
                    ),
                  );
                },
                child: Text("评价商品",
                    style: TextStyle(
                        fontSize: 14,
                        color: Color(int.parse('fa436a', radix: 16))
                            .withAlpha(255))),
              )),
        ],
      ),
    );
  }

  // 构建订单支付金额
  Container buildAmount(BoxDecoration boxDecoration, int index) {
    return Container(
      padding: const EdgeInsets.only(right: 15),
      height: 40,
      decoration: boxDecoration,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text("共",
              style: TextStyle(
                  fontSize: 13,
                  color: Color(int.parse('707070', radix: 16)).withAlpha(255))),
          Text(orderListData[index].orderDetailList.length.toString(),
              style: TextStyle(
                  fontSize: 13,
                  color: Color(int.parse('303133', radix: 16)).withAlpha(255))),
          Text("件商品 实付款",
              style: TextStyle(
                  fontSize: 13,
                  color: Color(int.parse('707070', radix: 16)).withAlpha(255))),
          Text(" ￥",
              style: TextStyle(
                  fontSize: 12,
                  color: Color(int.parse('707070', radix: 16)).withAlpha(255))),
          Text(orderListData[index].amount.toString(),
              style: TextStyle(
                  fontSize: 16,
                  color: Color(int.parse('303133', radix: 16)).withAlpha(255))),
        ],
      ),
    );
  }

  // 构建商品列表
  Column buildProductList(int index) {
    return Column(
      children: orderListData[index].orderDetailList.map((item) {
        return Container(
          padding: const EdgeInsets.only(right: 15, top: 15),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              CachedImageWidget(
                60,
                60,
                item.coverUrl,
                fit: BoxFit.cover,
              ),
              const SizedBox(
                width: 10,
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(item.name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 15,
                            color: Color(int.parse('303133', radix: 16))
                                .withAlpha(255))),
                    Text("单位: ${item.unit} x ${item.number}",
                        style: TextStyle(
                            fontSize: 13,
                            color: Color(int.parse('707070', radix: 16))
                                .withAlpha(255))),
                    Row(
                      children: [
                        Text("￥",
                            style: TextStyle(
                                fontSize: 12,
                                color: Color(int.parse('707070', radix: 16))
                                    .withAlpha(255))),
                        Text(item.price.toString(),
                            style: TextStyle(
                                fontSize: 15,
                                color: Color(int.parse('303133', radix: 16))
                                    .withAlpha(255))),
                      ],
                    )
                  ],
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  // 构建订单生成时间和订单状态
  Container buildCreateTime(BoxDecoration boxDecoration, int index) {
    return Container(
      padding: const EdgeInsets.only(right: 15),
      height: 40,
      decoration: boxDecoration,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Expanded(
            child: Text(orderListData[index].orderTime.toString(),
                style: TextStyle(
                    fontSize: 14,
                    color:
                        Color(int.parse('303133', radix: 16)).withAlpha(255))),
          ),
          Text(getOrderStatus(orderListData[index].status),
              style: TextStyle(
                  fontSize: 14,
                  color: Color(int.parse('fa436a', radix: 16)).withAlpha(255))),
          Visibility(
              visible: getDeleteStatus(orderListData[index].status),
              child: Container(
                margin: const EdgeInsets.only(left: 10),
                child: Image.asset(
                  "assets/images/delete.png",
                  height: 17,
                  width: 16,
                ),
              ))
        ],
      ),
    );
  }

  // 状态
  String getOrderStatus(int status) {
    Map statusMap = <int, String>{};
    statusMap[1] = "待付款";
    statusMap[2] = "待发货";
    statusMap[3] = "配送中";
    statusMap[4] = "已完成";
    statusMap[5] = "已取消";
    statusMap[6] = "退款";

    return statusMap[status];
  }

  // 是否显示删除图标
  bool getDeleteStatus(int status) {
    Map statusMap = <int, bool>{};
    statusMap[1] = false;
    statusMap[2] = false;
    statusMap[3] = false;
    statusMap[4] = true;
    statusMap[5] = true;
    statusMap[6] = true;

    return statusMap[status];
  }
}
